#!/bin/sh

# APP部署和启动脚本
# 1、上传JAR包（部署项目）、配置脚本（项目信息、JVM参数、部署文件）
# 2、执行命令：sh ./app.sh start/stop/restart(默认)/status/backup/deploy
# 3、请求接口：sh ./app.sh get xxx

# 项目信息
dir=/webapps/demoncat-core-web/
app=demoncat-core-web-0.0.1-SNAPSHOT.jar
port=8101
active=demo

# JVM参数
xms=500
xmx=500
xmn=168
xss=1024
ms=128
mms=1024

# 部署文件
tmp=/webapps/tmp/${app}

# 服务进程
pid=""
function query(){
  	pid=`ps -ef | grep ${app} | grep -v grep | awk '{print $2}'`
}

# 状态
function status(){
	query
	if [ -n "$pid" ]
	then
		echo "App is starting"
	else
		echo "App is stopping"
	fi
}

# 启动
function start(){
	query
    	if [ -n "$pid" ]
    	then
    		echo "App is started"
	else
		echo "App start ..."
		cd ${dir}
		nohup java -Xms${xms}m -Xmx${xmx}m -Xmn${xmn}m -Xss${xss}k -XX:MetaspaceSize=${ms}m -XX:MaxMetaspaceSize=${mms}m -XX:+HeapDumpOnOutOfMemoryError  -XX:HeapDumpPath=oom.hprof -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintHeapAtGC -Xloggc:gc.log -jar ${app} --spring.profiles.active=${active} > catalina.out 2>&1 &
		tail -f catalina.out
	fi
}

# 关闭
function stop(){
	query
	if [ -n "$pid" ]
	then
		# 优雅关闭
		echo "App http-stop ..."
		curl -X POST 127.0.0.1:${port}/actuator/shutdown
		echo ""
		# 等待守护进程
		for (( i=0; i<10; i++ ))
		do
			query
			if [ -n "$pid" ]
			then
				sleep 1s
			else
			  echo "App http-stop-${i}"
				break
			fi
		done
		# 强制关闭
		query
		if [ -n "$pid" ]
		then
			echo "App kill-stop ..."
			kill -9 $pid
		fi
		echo "App stopped"
	else
		echo "App is stopped"
	fi
}

# 重启
function restart(){
    stop
    start
}

# 备份
function backup(){
    # 创建目录
    echo "App backup ..."
    cd ${dir}
    if  [ ! -d "./backup" ]
    then
        mkdir backup
    fi
    # 备份JAR包
    if  [ -f "${app}" ]
    then
        cp ${app} backup/${app}-`date +%Y%m%d%H%M%S`
    fi
    echo "App backuped"
}

# 部署
function deploy(){
    # 查看
    echo "App deploy ..."
    echo "ip addr"
    ip addr
    echo "ls /webapps/tmp"
    ls -alh /webapps/tmp
    cd ${dir}
    echo "ls ${dir}"
    ls -alh
    # 关闭
    stop
	  # 备份
    backup
	  # 移动
    mv -f ${tmp} ./${app}
	  # 启动
    start
}

# 请求
function get(){
    curl -X GET 127.0.0.1:${port}/$1
}

# 命令
if [ "$1" = "" ];
then
    restart
else
	case $1 in
        start)
        start;;
        stop)
        stop;;
        restart)
        restart;;
        backup)
        backup;;
        deploy)
        deploy;;
        status)
        status;;
        get)
        get $2;;
        *)
	esac
fi
